<template>
  <div class="memo-wrap" style="height: 100%">
    <div class="btmline pagetitle" v-if="!isModule">
      <a-icon type="left" style="font-size: 20px" @click="goBack" />
      <div class="left2" style="cursor: pointer" @click="goBack">返回</div>
      <div>{{ pageTitle }}</div>
      <a-icon type="left" style="font-size: 20px; color: #fff" />
    </div>
    <a-layout class="mt24" style="height: 100%">
      <a-layout-sider :width="220" style="border-right: 1px solid #e8e8e8">
        <div class="pSlide-title">今日备忘</div>
        <a-menu class="groupleft">
          <a-menu-item
            v-for="item in groupList"
            :key="item.id"
            style="border-bottom: 1px solid #e8e8e8; margin: 0 10px"
            @click="changeStatus(item.id)"
          >
            <a-row type="flex" align="middle">
              <a-col class="groupname">{{ item.name }}({{ item.count }})</a-col>
            </a-row>
          </a-menu-item>
        </a-menu>
      </a-layout-sider>
      <a-layout style="height: 65vh">
        <a-row v-show="statusFlag === 0" type="flex" class="pl24">
          <a-date-picker :default-value="moment()" @change="changeDate" />
        </a-row>
        <!-- 备忘列表 -->
        <div
          v-show="statusFlag === 0"
          class="dash-title matter-title mt12"
          style="display: flex; align-items: flex-end; border: 1px solid reed; margin-bottom: 20px"
        >
          <div style="display: flex; align-items: center">
            <div class="bag-primary" style="margin-right: 12px"></div>
            <span>待办事项({{ memoData.memoListToday ? memoData.memoListToday.length : 0 }})</span>
          </div>
          <a-button icon="plus" type="primary" @click="addMemo">添加备忘</a-button>
        </div>
        <div v-show="statusFlag === 0" class="memolist" style="margin: 0 20px 20px 20px">
          <p v-if="memoData.memoListToday && memoData.memoListToday.length === 0" class="tip">当前暂无事项</p>
          <div v-for="(memo, index) in memoData.memoListToday" v-else :key="index" class="memo-item">
            <!-- <img :src="memo.completed ? checked : unchecked" alt="" @click="changeComplete(memo)" /> -->
            <i v-if="memo.completed" class="iconfont icon-wancheng2" @click="changeComplete(memo)" />
            <i v-else class="iconfont icon-dengdai" @click="changeComplete(memo)" />
            <div class="memo-left">
              <p>
                <span v-for="(people, idx) in memo.memoEmpDOList" :key="idx">
                  {{ people.empName }}
                  <span v-if="memo.memoEmpDOList.length - idx > 1" class="pr10">,</span>
                </span>
                {{ memo.content }}
              </p>
              <p>
                {{ memo.remindDate ? formatDate(memo.remindDate, "d") : "" }}
                {{ memo.remindTime.substring(0, 5) }}
              </p>
            </div>
            <div class="memo-right">
              <a type="link" :class="memo.completed ? 'colorC0C0C0' : 'link-color'" :disabled="memo.completed" @click="changeComplete(memo)"
                >完成</a
              >
              <a-divider type="vertical" />
              <a :class="memo.completed ? 'colorC0C0C0' : 'link-color'" type="link" :disabled="memo.completed" @click="editTheMemo(memo)"
                >编辑</a
              >
              <a-divider type="vertical" />
              <a class="link-color" type="link" @click="deleteTheMemo(memo)">删除</a>
            </div>
          </div>
        </div>
        <div v-show="statusFlag === 1" class="dash-title matter-title mt12" style="margin-bottom: 10px">
          <div style="display: flex; align-items: center">
            <div class="bag-primary" style="margin-right: 12px"></div>
            <span>延期事项（{{ memoData.memoListDelay ? memoData.memoListDelay.length : 0 }}）</span>
          </div>
        </div>
        <div v-show="statusFlag === 1" class="memolist" style="margin: 0 20px 20px 20px">
          <p v-if="memoData.memoListDelay && memoData.memoListDelay.length === 0" class="tip">当前暂无事项</p>
          <div v-for="(memo, index) in memoData.memoListDelay" v-else :key="index" class="memo-item">
            <img :src="delayed" alt />
            <div class="memo-left">
              <p>
                <span v-for="(people, idx) in memo.memoEmpDOList" :key="idx">
                  {{ people.empName }}
                  <span v-if="memo.memoEmpDOList.length - idx > 1" class="pr10">,</span>
                </span>
                {{ memo.content }}
              </p>
              <p>
                {{ memo.remindDate ? formatDate(memo.remindDate, "d") : "" }}
                {{ memo.remindTime.substring(0, 5) }}
              </p>
            </div>
            <div class="memo-right">
              <a :class="memo.completed ? 'colorC0C0C0' : 'link-color'" type="link" :disabled="memo.completed" @click="changeComplete(memo)"
                >完成</a
              >
              <a-divider type="vertical" />
              <a class="link-color" type="link" @click="editTheMemo(memo)">编辑</a>
              <a-divider type="vertical" />
              <a class="link-color" type="link" @click="deleteTheMemo(memo)">删除</a>
            </div>
          </div>
        </div>
      </a-layout>
    </a-layout>
    <!-- 添加备忘 -->
    <a-modal
      :title="modalTitle"
      :visible="addMemoVisible"
      :confirm-loading="confirmLoading"
      :destroy-on-close="true"
      @ok="confirmAddMemo"
      @cancel="addMemoVisible = false"
    >
      <a-form :form="memoForm">
        <a-form-item label>
          <a-textarea
            v-decorator="[
              'content',
              {
                rules: [{ required: true, message: '请输入备忘' }]
              }
            ]"
            placeholder="请输入备忘"
            :auto-size="{ minRows: 5, maxRows: 10 }"
          />
        </a-form-item>
        <a-form-item label="用工单位" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <!-- companyId -->
          <a-select
            v-decorator="[
              'companyId',
              {
                rules: [{ required: true, message: '请选择用工单位' }]
              }
            ]"
            placeholder="请选择用工单位"
            style="width: 300px"
          >
            <a-select-option v-for="(item, index) in selectOptions" :key="index" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="提醒模式" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-radio-group
            v-decorator="[
              'remindType',
              {
                initialValue: remindType,
                rules: [{ required: true, message: '请选择提醒模式' }]
              }
            ]"
            @change="onRemindTypeChange"
          >
            <a-radio :value="1">固定日期提醒</a-radio>
            <a-radio :value="2">周期性提醒</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item :label="remindType === 1 ? '固定日期提醒' : '周期性提醒'" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
          <a-date-picker
            v-show="remindType === 1"
            v-decorator="['remindDate', { initialValue: initRemindDate }]"
            :disabled-date="disabledDate"
          />
          <span v-show="remindType === 2">
            每月
            <a-select
              v-decorator="[
                'remindMonthUnitValue',
                {
                  initialValue: 1,
                  rules: [{ required: true, message: '请选择提醒时间' }]
                }
              ]"
              :options="dayList"
              mode="multiple"
              style="width: 80px"
            />
            号
          </span>
          <a-time-picker v-decorator="['remindTime', { initialValue: initRemindTime }]" style="margin-left: 24px" format="HH:mm" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 删除确定 -->
    <a-modal v-model="deleteVisible" title="确定" @ok="handleDelete">
      <p>确定删除该事项吗？</p>
    </a-modal>
    <!-- 确认完成 -->
    <a-modal v-model="confirmVisible" title="确定" @ok="handleConfirm">
      <p>确定已完成该事项吗？</p>
    </a-modal>
  </div>
</template>
<script>
import unchecked from "@/assets/img/unfinish.png";
import checked from "@/assets/img/finish.png";
import delayed from "@/assets/img/gantan.png";
import moment from "moment";
import { getMemoListAll, addMemoConfigsReq, finishMemoConfigsReq, updateMemo, deleteMemo } from "@/api/company/news";

const dayList = [];
for (let i = 1; i < 32; i++) {
  dayList.push({
    label: i + "",
    value: i + ""
  });
}

export default {
  components: {},
  props: ["isModule", "companyIdVal"],
  data() {
    return {
      dayList,
      remindType: 1,
      remindDisabled: false,
      timeParams: "",
      moment,
      unchecked,
      checked,
      delayed,
      pageTitle: "今日备忘",
      groupList: [
        { id: 0, name: "今日待办", count: 0 },
        { id: 1, name: "延期事项", count: 0 }
      ],
      isRemind: [
        { value: false, label: "不提醒" },
        { value: true, label: "提醒" }
      ],
      remindlist: [
        { value: 1, label: "实时" },
        { value: 2, label: "5分钟前" },
        { value: 3, label: "15分钟前" },
        { value: 4, label: "30分钟前" },
        { value: 5, label: "1小时前" },
        { value: 6, label: "2小时前" },
        { value: 7, label: "1天前" },
        { value: 8, label: "2天前" },
        { value: 9, label: "一周前" }
      ],
      addMemoVisible: false,
      deleteVisible: false,
      confirmVisible: false,
      confirmLoading: false,
      modalTitle: "添加备忘",
      statusFlag: 0,
      memoForm: this.$form.createForm(this),
      memoData: {},
      memoListDelay: [],
      memoListToday: [],
      initRemindDate: "",
      initRemindTime: "",
      chooseMemberVisible: false,
      selectedList: [],
      defaultSelectedKeys: [],
      memoEmpDOList: [],
      defaultSelectedNames: "",
      dateParams: moment(new Date()).format("YYYY-MM-DD"),
      currentRemindTime: moment(new Date()).format("HH:mm")
    };
  },
  computed: {
    selectOptions() {
      return this.$store.state.hr.companyList;
    }
  },
  watch: {
    companyIdVal: {
      handler() {
        this.companyId = this.companyIdVal;
        this.getMemoListAll();
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.companyId = this.$store.state.hr.companyId;
    this.companyName = this.$store.state.hr.companyName;
    this.initRemindDate = moment(new Date(), "YYYY-MM-DD");
    this.initRemindTime = moment(new Date(), "HH:mm");
    this.selectDate = moment(new Date()).format("YYYY-MM-DD");
    this.currentRemindTime = moment(new Date()).format("HH:mm");
  },
  mounted() {},
  methods: {
    onRemindTypeChange(evt) {
      this.remindType = evt.target.value;
    },
    remindChange(e) {
      if (e === false) {
        this.remindDisabled = true;
      }
      if (e === true) {
        this.remindDisabled = false;
      }
    },
    disabledDate(current) {
      return current && current < moment().subtract(1, "days");
    },
    goBack() {
      this.$router.go(-1);
    },
    changeStatus(e) {
      this.statusFlag = e;
    },
    changeDate(data, timeString) {
      this.selectDate = timeString;
      this.currentRemindTime = moment(new Date()).format("HH:mm");
      this.getMemolisyByDate(this.selectDate);
      if (data) {
        this.initRemindDate = moment(data._d, "YYYY-MM-DD");
        this.initRemindTime = moment(data._d, "HH:mm");
      }
      this.currentRemindDate = data;
      this.dateParams = this.selectDate;
      this.timeParams = this.currentRemindTime;
      // this.companyId = this.companyId
      this.getMemoListAll();
    },
    handleConfirm() {
      if (this.currentMemo.completed === false) {
        var memoInfoUpdateDTO = {
          id: this.currentMemo.id,
          completed: true,
          companyId: this.currentMemo.companyId
        };
        finishMemoConfigsReq(memoInfoUpdateDTO).then((res) => {
          this.$message.success("编辑成功");
          this.confirmVisible = false;
          this.getMemoListAll(this.companyId);
        });
      }
    },
    changeComplete(memo) {
      if (!memo.completed) {
        this.confirmVisible = true;
      }
      this.currentMemo = memo;
    },
    getMemolisyByDate(selectDate) {
      getMemoListAll({
        companyId: this.companyId,
        remindDate: selectDate,
        remindTime: this.currentRemindTime
      }).then((res) => {
        this.memoData = res.data;
        this.groupList.find((item) => item.id === 0).count = res.data.memoCountToday;
        this.groupList.find((item) => item.id === 1).count = res.data.memoCountDelay;
        this.memoListToday = res.data.memoListToday;
        this.memoListDelay = res.data.memoListDelay;
      });
    },
    getMemoListAll(companyId) {
      const data = {};
      if (this.dateParams) {
        data.remindDateStart = this.dateParams + " 00:00:00";
        data.remindDateEnd = this.dateParams + " 59:59:59";
        data.companyId = this.companyId;
      }
      // console.log("data", data);
      getMemoListAll(data).then((res) => {
        this.memoData = res.data;
        this.groupList.find((item) => item.id === 0).count = res.data.memoCountToday;
        this.groupList.find((item) => item.id === 1).count = res.data.memoCountDelay;
        this.memoListToday = res.data.memoListToday;
        this.memoListDelay = res.data.memoListDelay;
      });
    },
    addMemo() {
      this.remindDisabled = false;
      this.addMemoVisible = true;
      this.modalTitle = "添加备忘";
      this.memoForm.resetFields();
      this.defaultSelectedKeys = [];
      this.defaultSelectedNames = [];
      this.memoEmpDOList = [];
      this.initRemindDate = this.currentRemindDate ? moment(this.currentRemindDate, "YYYY-MM-DD") : moment(new Date(), "YYYY-MM-DD");
      this.initRemindTime = this.currentRemindDate ? moment(this.currentRemindDate, "HH:mm:ss") : moment(new Date(), "HH:mm");
      this.dateParams = this.selectDate ? this.selectDate : moment(new Date()).format("HH:mm:ss");
      this.currentRemindTime = this.timeParams ? this.timeParams : moment(new Date()).format("HH:mm:ss");
    },
    confirmAddMemo(e) {
      var that = this;
      e.preventDefault();
      that.memoForm.validateFields((err, values) => {
        values.remindDate = moment(values.remindDate).format("YYYY-MM-DD");
        values.remindTime = moment(values.remindTime).format("HH:mm") + ":00";
        values.remindNeed = 1;
        values.remindBefore = 1;
        if (!err) {
          that.addMemoVisible = false;
          if (that.modalTitle === "添加备忘") {
            var memoInfoAddDTO = {
              ...values,
              remind_unit: "MONTH",
              memoEmpDOList: that.memoEmpDOList
            };
            if (memoInfoAddDTO["remindType"] === 2 && memoInfoAddDTO["remindMonthUnitValue"]) {
              memoInfoAddDTO["remindMonthUnitValue"] = memoInfoAddDTO["remindMonthUnitValue"].join(",");
            } else {
              delete memoInfoAddDTO["remindMonthUnitValue"];
            }
            addMemoConfigsReq(memoInfoAddDTO).then((res) => {
              that.$message.success("添加成功");
              that.getMemoListAll(that.companyId);
            });
          } else {
            var memoInfoUpdateDTO = {
              ...values,
              id: that.currentMemo.id,
              remind_unit: "MONTH",
              memoEmpDOList: that.memoEmpDOList
            };
            if (memoInfoUpdateDTO["remindType"] === 2 && memoInfoUpdateDTO["remindMonthUnitValue"]) {
              memoInfoUpdateDTO["remindMonthUnitValue"] = memoInfoUpdateDTO["remindMonthUnitValue"].join(",");
            } else {
              delete memoInfoUpdateDTO["remindMonthUnitValue"];
            }
            updateMemo(memoInfoUpdateDTO).then((res) => {
              that.$message.success("编辑成功");
              that.getMemoListAll(that.companyId);
            });
          }
        }
      });
    },
    async editTheMemo(record) {
      const theDetail = await this.$request({
        url: `/hr/api/v1/memoInfos/${record.id}`
      })
        .then((res) => {
          return res.data;
        })
        .catch((err) => {
          console.log(err);
          return false;
        });
      if (!theDetail) {
        this.$message.error("记录详情加载失败");
        return false;
      }

      this.remindType = theDetail.remindType;
      this.remindDisabled = false;
      this.modalTitle = "编辑备忘";
      this.addMemoVisible = true;
      this.currentMemo = theDetail;
      this.initRemindDate = moment(theDetail.remindDate, "YYYY-MM-DD");
      this.initRemindTime = moment(theDetail.remindTime, "HH:mm");

      setTimeout(() => {
        const remindMonthUnitValue = theDetail.remindMonthUnitValue ? theDetail.remindMonthUnitValue.split(",") : 1;
        this.memoForm.setFieldsValue({
          content: theDetail.content,
          remindBefore: theDetail.remindBefore,
          companyId: theDetail.companyId,
          remindNeed: theDetail.remindNeed ? "提醒" : "不提醒",
          remindDate: moment(theDetail.remindDate).format("YYYY-MM-DD"),
          remindTime: moment(theDetail.remindTime, "HH:mm"),
          remindType: theDetail.remindType,
          remindMonthUnitValue
        });
      }, 0);
      if (theDetail.remindNeed === false) {
        this.remindDisabled = true;
      }
      if (theDetail.remindNeed === true) {
        this.remindDisabled = false;
      }
      this.defaultSelectedKeys = [];
      this.defaultSelectedNames = [];
      theDetail.memoEmpDOList.forEach((item) => {
        this.defaultSelectedKeys.push(item.empId);
        this.defaultSelectedNames.push(item.empName);
      });
    },
    deleteTheMemo(record) {
      this.deleteVisible = true;
      this.currentMemo = record;
    },
    handleDelete() {
      var memoInfoIds = [];
      memoInfoIds.push(this.currentMemo.id);
      deleteMemo(memoInfoIds).then((res) => {
        this.$message.success("删除成功");
        this.deleteVisible = false;
        this.getMemoListAll(this.companyId);
      });
    },
    memberSelectedChange(list) {
      this.memoEmpDOList = list;
      this.memoEmpDOList.forEach((item) => {
        item.empName = item.name;
        item.empId = item.id;
        item.id = null;
      });
      this.defaultSelectedKeys = list.map((item) => item.id);
      this.defaultSelectedNames = list.map((item) => item.name);
    }
  }
};
</script>
<style lang="scss">
.memo-wrap {
  .iconfont {
    color: var(--primary);
  }
  .pagetitle {
    height: 64px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    font-weight: 400;
    color: #595959;
    line-height: 64px;
    padding: 0 20px;
    cursor: pointer;
  }
  .left2 {
    z-index: 3;
    left: 50px;
    position: absolute;
    color: #595959;
    font-size: 16px;
  }
  .pSlide-title {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    text-align: left;
    color: #000000;
    padding: 0 24px;
    cursor: pointer;
  }
  .matter-title {
    padding: 0 24px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .link-color {
    color: var(--primary);
  }
  .colorC0C0C0 {
    color: #c0c0c0;
  }
  .bag-primary {
    width: 4px;
    height: 20px;
    background: var(--primary);
    border-radius: 2px;
  }
}
.top_img {
  width: 25px;
  height: 25px;
}
</style>
